import 'package:flutter/material.dart';
import 'package:food_hub_app/widgets/common/index.dart';

class YearSelector extends StatefulWidget {
  final int initialYear;
  final int? minYear;
  final int? maxYear;
  final Function(int) onYearChanged;

  const YearSelector({
    super.key,
    required this.initialYear,
    required this.onYearChanged,
    this.minYear,
    this.maxYear,
  });

  @override
  State<YearSelector> createState() => _YearSelectorState();
}

// SingleTickerProviderStateMixin 动画控制器
class _YearSelectorState extends State<YearSelector>
    with SingleTickerProviderStateMixin {
  late int _currentYear;

  // 用于动画效果
  late AnimationController _animationController;
  late Animation<double> _scaleAnimation;

  @override
  void initState() {
    super.initState();
    _currentYear = widget.initialYear;

    // 初始化动画控制器
    _animationController = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 200),
    );

    // 缩放动画
    _scaleAnimation = Tween<double>(begin: 1.0, end: 1.1).animate(
      CurvedAnimation(parent: _animationController, curve: Curves.easeInOut),
    );
  }

  @override
  void dispose() {
    _animationController.dispose();
    super.dispose();
  }

  /// 切换到上一年
  void _previousYear() {
    if (widget.minYear == null || _currentYear > widget.minYear!) {
      _animateYearChange(() {
        setState(() {
          _currentYear--;
        });
        widget.onYearChanged(_currentYear);
      });
    }
  }

  /// 切换到下一年
  void _nextYear() {
    if (widget.maxYear == null || _currentYear < widget.maxYear!) {
      _animateYearChange(() {
        setState(() {
          _currentYear++;
        });
        widget.onYearChanged(_currentYear);
      });
    }
  }

  /// 年份变化时的动画效果
  void _animateYearChange(VoidCallback onComplete) {
    _animationController.forward().then((_) {
      onComplete();
      _animationController.reverse();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        circleIconButton(
          context: context,
          icon: Icons.chevron_left,
          onPressed: () => _previousYear(),
        ),
        // 年份显示
        AnimatedBuilder(
          animation: _scaleAnimation,
          builder: (context, child) {
            return Transform.scale(scale: _scaleAnimation.value, child: child);
          },
          child: Text(
            '$_currentYear',
            style: TextStyle(
              fontSize: 24,
              fontWeight: FontWeight.bold,
              color: Theme.of(context).primaryColor,
            ),
          ),
        ),
        circleIconButton(
          context: context,
          icon: Icons.chevron_right,
          onPressed: () => _nextYear(),
        )
      ],
    );
  }
}
